<template>
  <div class="warpper-box">
    <div class="inner_box">
      <el-form :inline="true" size="small" :model="formInline" ref="formInline">
        <el-form-item label="考核周期" prop="time">
          <el-date-picker
            v-model="formInline.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="库类别" prop="applyCategoryId">
          <el-cascader
            placeholder="支持搜索，多选"
            filterable
            v-model="formInline.applyCategoryId"
            collapse-tags
            :options="treeData"
            :props="{ multiple: true, emitPath: false }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="loadList(true)"
            >搜索</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="reset('formInline')"
            >重置</el-button
          >
          <el-button type="primary" icon="el-icon-plus" @click="add(true)"
            >新增</el-button
          >
          <el-button type="danger" icon="el-icon-delete" :disabled="selectItem.length == 0" @click="delBatch()">批量删除</el-button>
          <el-button type="primary" icon="el-icon-upload" :disabled="tables.tableData.length == 0" @click="xlsxExport()">导出Excel</el-button>
        </el-form-item>
      </el-form>
      <supplier-common-list
        ref="createSupplier"
        :tableData="tables.tableData"
        :tableLabel="tables.tableLabel"
        :models="tables"
        :key="tableKey"
        @on-search-click="loadList"
        @on-selection-click="selectionChange"
        @on-detail-click="supplierDetailClick"
        @on-evaluateDetail-click="evaluateDetailClick"
        @on-edit-click="add"
      />
    </div>
    <supplierDetail ref="createSupplierDetail" />
    <evaluateForm ref="createEvaluateForm" @onOk="loadList"/>
    <evaluateDetail ref="createEvaluateDetail" />
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import {
  getEvaluationPage,
  getSupplierStorePage,
  getSupplierCategoryTree,
  getEvaluationDel
} from "@/api/supplier_api";
import { checkEmail, checkPhone, TreeArrar } from "@/utils/index";
import { EVALUATE_BUILDING_LABEL } from "@/views/supplier/supplierModel/config";
import supplierDetail from "./supplier_detail.vue";
import supplierCommonList from "@/views/supplier/supplierModel/supplier_common_list.vue";
import evaluateForm from "./evaluate_form.vue";
import evaluateDetail from "./evaluate_detail.vue";
export default {
  components: {
    supplierDetail,
    supplierCommonList,
    evaluateForm,
    evaluateDetail,
  },
  data() {
    return {
      formInline: {
        name: "",
        applyCategoryId: "",
        contactPerson: "",
        time: []
      },
      treeData: [],
      tableKey: 0,
      tables: {
        total: 0,
        isStore: true,
        tableData: [],
        tableLabel: EVALUATE_BUILDING_LABEL
      },
      models: {
        pageNum: 1,
        pageSize: 10
      },
      tips:'泸州老窖发展投资集团有限公司（服务类）',
      //tips:'（服务类）',
      selectItem:[]
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.loadList(true);
    this.categoryList();
  },
  methods: {
    async categoryList() {
      const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
        if (data && data.length) {
          let NewData = data.map(ele => TreeArrar(ele));
          this.treeData = NewData;
        }
      }
    },
    async loadList(formData) {
      let param = {};
      if (typeof formData === "boolean") {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected();
        }
      }
      if (typeof formData === "object") {
        this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected();
        }
      }
      if (
        this.formInline.applyCategoryId &&
        this.formInline.applyCategoryId.length
      ) {
        param.applyCategoryId = this.formInline.applyCategoryId.join(",");
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.evaluationTimeStart = this.formInline.time[0];
        param.evaluationTimeEnd = this.formInline.time[1];
      }

      param.name = this.formInline.name;
      param.pageNum = this.models.pageNum;
      param.pageSize = this.models.pageSize;
      param.supplierCategory = '2'
      const { code, data } = await getEvaluationPage(param);
      if (code == 200) {
        let res = data?.list ?? []
          res.forEach(v => {
          v.evaluateEdit = true
          v.evaluateDetail = true
          v.isShowEdit = false
          if (v.isPaused == 1 || v.tag == '3') {
            v.isShowEdit = true
          }
        })
        this.tables.tableData = res
        this.tables.total = data?.total ?? 0
      }
    },
    onOk(result) {
      this.tableKey++;
      this.loadList(result);
    },
    reset(formName) {
      this.$refs[formName].resetFields();
      this.loadList(true);
    },
    selectionChange(arr){
        this.selectItem = arr;
      },
    async delBatch() {
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
      }
       let p = 0;
      for (let i = 0; i < this.selectItem.length; i++){
        let item = this.selectItem[i]
        let param = {}
        param.id = item.id
        const { code } = await getEvaluationDel(param);
        if (code == 200) {
          p++
        }
      }
      if (p == this.selectItem.length) {
        this.$message.success('删除成功');
        this.loadList(true);
      }
    },
    supplierDetailClick(row) {
      this.$refs.createSupplierDetail.openDetail(row);
    },
    evaluateDetailClick(row) {
      this.$refs.createEvaluateDetail.openForm(
        row,
       this.tips
      );
    },
    async add(row) {
       let param = {};
        param.queryType = this.findType["pass"];
         param.isPaused = 0
        param.storeStatus = "1"
        param.pageSize = 2000
         param.pageNum = 1
        const {data} = await getSupplierStorePage(param)
        let result = []
        data.list.forEach(v => {
          let ids = result.map(v => v.id)
          if (!ids.includes(v.id)) {
            result.push(v)
          }
        })
      if (typeof row === "boolean") {
          this.$refs.createEvaluateForm.openForm(
            result,
            row,
            this.tips,
            "2"
          );
      
      } else {
        this.$refs.createEvaluateForm.openForm(
          result,
          row,
          this.tips,
          "2"
        );
      }
    },
    async xlsxExport() {
      let param = {};
      if (
        this.formInline.applyCategoryId &&
        this.formInline.applyCategoryId.length
      ) {
        param.applyCategoryId = this.formInline.applyCategoryId.join(",");
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.evaluationTimeStart = this.formInline.time[0];
        param.evaluationTimeEnd = this.formInline.time[1];
      }

      param.name = this.formInline.name;
      param.pageNum = 1;
      param.pageSize = this.tables.total;
      param.supplierCategory = '2'
      const { code, data } = await getEvaluationPage(param);
      if (code == 200) {
        let fields = {}
        EVALUATE_BUILDING_LABEL.forEach(v => {
        if (v.type == 'on') {
          fields['index'] = v.label
        } else {
          if (v.prop) {
            fields[v.prop] = v.label
          }
        }
        })
        const entries = Object.entries(fields);
        if (entries.length > 0) {
          const firstEntry = entries.shift();
          entries.push(firstEntry);
        }
      const header = Object.fromEntries(entries);
        const manualWidthColumns = [
          { width: 10 },
          { width: 40 },
          { width: 35 },
          { width: 35 },
          { width: 20 },
          { width: 20 }
        ];

        data.list.forEach((v, i) => {
          v.index = (i + 1)
          if (v.evaluationStartDate) {
            let startTime = moment(v.evaluationStartDate).format("YYYY-MM-DD");
            let endTime = moment(v.evaluationEndDate).format("YYYY-MM-DD");
            v.evaluationStartDate = startTime + ' 至 ' + endTime
          }
          if (v.createTime) {
            let time = moment(v.createTime).format("YYYY-MM-DD");
            v.createTime = time
          }
        })
        
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
          this.$refs.createSupplier.exportXlsx(header,data.list,manualWidthColumns,'服务类明细')
        }
      }
    },
  }
};
</script>
<style scoped>
.duo-file {
  display: flex;
  flex-wrap: wrap;
}
</style>

<!--

 this.$refs.createEvaluateForm.openForm('泸州老窖发展投资集团有限公司（服务类）')

   
      this.$refs.creatEevaluateDetail.openForm(row,'泸州老窖发展投资集团有限公司（服务类）')

    <supplierDetail ref="createSupplierDetail" />
    <evaluateForm ref="createEvaluateForm"/>
    <evaluateDetail ref="createEvaluateDetail" />


import supplierDetail from '@/views/supplier/supplierModel/supplier_detail.vue'
import evaluateForm from './evaluate_form.vue'
import evaluateDetail from './evaluate_detail.vue'
  components: {
        supplierDetail,
        evaluateForm,
    evaluateDetail
  },
    async categoryList() {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
            let NewData = data.map((ele) => TreeArrar(ele))
     }
    },
        async add(row) {
            if (typeof row === 'boolean') {
                this.$refs.createEvaluateForm.openForm('泸州老窖发展投资集团有限公司（服务类）')
            } else {
             this.$refs.createEvaluateDetail.openForm(row,'泸州老窖发展投资集团有限公司（服务类）')
        }
     },
-->
